package com.cskaoyan.service.wxService;

import com.cskaoyan.bean.Goods;
import com.cskaoyan.bean.GoodsExample;
import com.cskaoyan.bean.Topic;
import com.cskaoyan.bean.TopicExample;
import com.cskaoyan.mapper.GoodsMapper;
import com.cskaoyan.mapper.TopicMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxTopicServiceImpl implements WxTopicService{

    @Autowired
    TopicMapper topicMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public List<Topic> wxTopicRelated(Integer id) {
        PageHelper.startPage(0,4);
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause("read_count desc");
        topicExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(id);
        return topicMapper.selectByExample(topicExample);
    }

    @Override
    public Map wxTopicList(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause("add_time desc");
        topicExample.createCriteria().andDeletedEqualTo(false);
        List<Topic> topicList = topicMapper.selectByExample(topicExample);
        PageInfo<Topic> pageInfo = new PageInfo<>(topicList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",topicList);
        map.put("count",pageInfo.getPages());
        return map;
    }

    @Override
    public Map wxTopicDetail(Integer id) {
        Topic topic = topicMapper.selectByPrimaryKey(id);
        String[] goodsId = topic.getGoods();
        //字符数组转换为Integer数组
        Integer[] goodsId1 = (Integer[]) ConvertUtils.convert(goodsId,Integer.class);
        List<Goods> goods = null;
        if (goodsId != null && goodsId.length >0){
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.createCriteria().andDeletedEqualTo(false).andIdIn(Arrays.asList(goodsId1));
            goods = goodsMapper.selectByExample(goodsExample);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("topic",topic);
        map.put("goods",goods);
        return map;
    }
}
